package com.answer.controller.search;

import com.answer.controller.system.QuestionController;
import com.answer.lucenu.QuestionIndex;
import com.answer.model.Question;
import com.answer.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by Administrator on 2017/5/2.
 */
@Controller
@RequestMapping("/search")
public class SearchController {
    private static final Logger log = LoggerFactory.getLogger(SearchController.class);
    //索引
    private QuestionIndex questionIndex = new QuestionIndex();

    @RequestMapping(value = "/q")
    public ModelAndView search(@RequestParam(value = "key", required = false) String key,
                               @RequestParam(value = "pageIndex", required = false) String pageIndex,
                               HttpServletRequest request) throws Exception {
        ModelAndView mv = new ModelAndView();
        try {
            if (StringUtil.isEmpty(pageIndex)) {
                pageIndex = "1";
            }
            if (StringUtil.isEmpty(key)) {
                key = "";
            }
            List<Question> quesList = questionIndex.searchQuestion(key);
            Integer toIndex = quesList.size() >= Integer.parseInt(pageIndex) * 10 ? Integer.parseInt(pageIndex) * 10 : quesList.size();
            mv.addObject("mainPage", "article/result.jsp");
            mv.addObject("quesList", quesList.subList((Integer.parseInt(pageIndex) - 1) * 10, toIndex));
            mv.addObject("key", key);
            mv.addObject("resultTotal", quesList.size());
            mv.addObject("pageTitle", "搜索关键字'" + key + "'结果页面");
            mv.setViewName("mainTemp");
            return mv;
        } catch (Exception e) {
            e.printStackTrace();
            return mv;
        }
    }
}
